<template>
    <div>
        <!-- 表头分页查询条件， shadow="never" 指定 card 卡片组件没有阴影 -->
        <el-card shadow="never" class="mb-5">
            <!-- flex 布局，内容垂直居中 -->
            <div class="flex items-center">
                <el-text>文章标题</el-text>
                <div class="ml-3 w-52 mr-5">
                    <el-input v-model="searchArticleName" placeholder="请输入（模糊查询）" />
                </div>

                <el-text>创建日期</el-text>
                <div class="ml-3 w-30 mr-5">
                    <!-- 日期选择组件（区间选择） -->
                    <el-date-picker v-model="pickDate" type="daterange" range-separator="至" start-placeholder="开始时间"
                        end-placeholder="结束时间" size="default" :shortcuts="shortcuts" @change="datepickerChange" />
                </div>

                <el-button type="primary" class="ml-3" :icon="Search" @click="getTableData">查询</el-button>
                <el-button class="ml-3" :icon="RefreshRight" @click="reset">重置</el-button>
            </div>
        </el-card>
        <el-card shadow="never">
            <!-- 新增按钮 -->
            <div class="mb-5 flex items-center">
                <el-button type="primary" @click="router.push('/admin/publish/article/edit')">
                    <el-icon class="mr-1">
                        <EditPen />
                    </el-icon>
                    写文章</el-button>
            </div>

            <!-- 分页列表 -->
            <el-table :data="tableData" :default-sort="{ prop: 'articleName', order: 'descending' }" border stripe
                style="width: 100%" v-loading="tableLoading">
                <el-table-column type="selection" width="45" />
                <el-table-column type="index" label="序号" width="60" />
                <el-table-column prop="id" label="文章编号" width="180" />
                <el-table-column prop="title" label="文章标题" sortable width="180" />
                <el-table-column prop="cover" label="文章封面" sortable width="180">
                    <template #default="scope">
                        <el-image style="width: 64px;" :src="scope.row.cover" />
                    </template>
                </el-table-column>
                <el-table-column prop="isTop" label="是否置顶" width="100">
                    <template #default="scope">
                        <el-switch
                            @change="handleIsTopChange(scope.row)"
                            v-model="scope.row.isTop"
                            inline-prompt
                            :active-icon="Check"
                            :inactive-icon="Close"
                        />
                    </template>
                </el-table-column>
                <el-table-column prop="createTime" label="首发时间" width="180" />
                <el-table-column label="文章操作">
                    <template #default="scope">
                        <el-button type="success" size="small" @click="goArticleDetailPage(scope.row.id)">
                            <el-icon class="mr-1">
                                <View />
                            </el-icon>
                            浏览
                        </el-button>

                        <el-button type="primary" size="small" @click="router.push('/admin/update/article/edit/' + (scope.row.id))">
                            <el-icon class="mr-1">
                                <Edit />
                            </el-icon>
                            修改
                        </el-button>
                        <el-button type="danger" size="small" @click="deleteArticleSubmit(scope.row)">
                            <el-icon class="mr-1">
                                <Delete />
                            </el-icon>
                            删除
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>
            <!-- 分页 -->
            <div class="mt-10 flex justify-center">
                <el-pagination v-model:current-page="current" v-model:page-size="size" :page-sizes="[5, 10, 20, 50]"
                    :small="false" :background="true" layout="total, sizes, prev, pager, next, jumper" :total="total"
                    @size-change="handleSizeChange" @current-change="getTableData" />
            </div>
        </el-card>
        <FormDialog ref="formDialogRef" title="添加标签" destroyOnClose @submit="onSubmit">
            <el-form ref="formRef" :rules="rules" :model="form">
                <el-form-item label="标签名" prop="name" label-width="100px">
                    <!-- 输入框组件 -->
                    <el-input size="large" v-model="form.name" placeholder="请输入标签名(1-16个字符范围内)" maxlength="16"
                        show-word-limit clearable />
                </el-form-item>
            </el-form>
        </FormDialog>

        <FormDialog ref="formDialogPlusRef" title="批量添加标签" destroyOnClose @submit="onPlusSubmit">
            <el-form ref="InputRef" :model="plusForm">
                <el-form-item label="标签集合" prop="name" label-width="120px">
                    <!-- 输入框组件 -->
                    <div class="flex items-center gap-2">
                        <el-tag v-for="article in dynamicArticles" :key="article" closable :disable-transitions="false"
                            type="success" @close="handleClose(article)">
                            {{ article }}
                        </el-tag>

                        <span class="w-20">
                            <el-input v-if="inputVisible" ref="InputRef" v-model="inputValue" class="w-20" size="small"
                                @keyup.enter="handleInputConfirm" @blur="handleInputConfirm" />
                            <el-button v-else class="button-new-tag" size="small" @click="showInput">
                                + 新增标签
                            </el-button>
                        </span>
                    </div>
                </el-form-item>
            </el-form>
        </FormDialog>
    </div>
</template>

<script setup>
// 引入所需图标
import { Search, RefreshRight, Upload, EditPen, ArrowLeft } from '@element-plus/icons-vue'
import { dateEquals } from 'element-plus';
import { Check, Close } from '@element-plus/icons-vue'
import moment from 'moment';
import { ref, reactive, nextTick, watch } from 'vue';

//表格数据加载动画
const tableLoading = ref(false)

// 分页查询的分类名称
const searchArticleName = ref('')
// 日期
const pickDate = ref('')

//起始时间
const startDate = reactive({})
//结束时间
const endDate = reactive({})
//监听日期组件改变事件，并将开始结束时间设置到变量中
const datepickerChange = (e) => {
    startDate.value = moment(e[0]).format('YYYY-MM-DD')
    endDate.value = moment(e[1]).format('YYYY-MM-DD')
    console.log("开始时间：" + startDate.value + " 结束时间：" + endDate.value)
}

//近期时间
const shortcuts = [
    {
        text: '最近一天',
        value: () => {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 1000 * 3600 * 24 * 1)
            return [start, end]
        }
    },
    {
        text: '最近三天',
        value: () => {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 1000 * 3600 * 24 * 3)
            return [start, end]
        }
    },
    {
        text: '最近一周',
        value: () => {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 1000 * 3600 * 24 * 7)
            return [start, end]
        }
    },
    {
        text: '最近一个月',
        value: () => {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 1000 * 3600 * 24 * 30)
            return [start, end]
        }
    },
    {
        text: '最近三个月',
        value: () => {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 1000 * 3600 * 24 * 90)
            return [start, end]
        }
    },
    {
        text: '最近六个月',
        value: () => {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 1000 * 3600 * 24 * 180)
            return [start, end]
        }
    },
    {
        text: '最近一年',
        value: () => {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 1000 * 3600 * 24 * 365)
            return [start, end]
        }
    }
]

import { publishArticle, getArticlePageList, deleteArticle, viewArticle, updateArticle, autoSaveArticle, setArticleTop } from '@/api/admin/article';
import { showMessage, showModel } from '@/composables/utils';
// 引入md - editor - v3编辑器
import { MdEditor } from 'md-editor-v3';
import 'md-editor-v3/lib/style.css'
import { uploadFile } from '@/api/admin/file';
import { getCategoryList } from '@/api/admin/category';
import { getTagSelectList, searchLikeTagName } from '@/api/admin/tag';
import { useRouter } from 'vue-router';

//路由
const router = useRouter()

// 表格数据         
const tableData = ref([])
// 当前页码，给了一个默认值 1
const current = ref(1)
// 总数据量，给了个默认值 0
const total = ref(0)
// 每页显示的数据量，给了个默认值 10
const size = ref(10)
 // 每页展示数量变更事件
 const handleSizeChange = (chooseSize) => {
    size.value = chooseSize
    getTableData()
}
//获取分页数据
function getTableData() {
    //显示表格loading
    tableLoading.value = true
    //调用后台接口，传入所需参数
    const reqParams = {
        current: current.value,
        size: size.value,
        startDate: startDate.value,
        endDate: endDate.value,
        title: searchArticleName.value
    }
    getArticlePageList(reqParams).then((res) => {
        if (res.success == true) {
            //获取数据成功
            console.log('获取文章列表')
            tableData.value = res.data
            current.value = res.pageIndex
            size.value = res.size
            total.value = res.total
            
        }
    }).finally(() => {tableLoading.value = false})
}

//重置
function reset() {
    searchArticleName.value = ''
    pickDate.value = ''
    startDate.value = null
    endDate.value = null
}
//进入页面获取数据
getTableData()

//删除对应的文章
function deleteArticleSubmit(row) {
    //获取对应的id
    console.log(row)
    let id = row.id;

    showModel("是否确认删除文章：" + row.title, "warning", "温馨提示：").then(() => {
        //发送删除请求
        deleteArticle({ id: id }).then((res) => {
            if (res.success == true) {
                let message = "标题为" + row.title + "的文章已删除！"
                console.log(message)
                showMessage(message)
                //刷新数据
                getTableData()
            } else {
                let message = res.message
                showMessage(message, 'warning')
            }
        })

    }).catch(() => {
        let message = "删除文章操作已取消！删除文章标题为：" + row.title
        showMessage(message, 'error')
    })

}

// 设置文章置顶
const handleIsTopChange = (row) => {
    // 构建请求体
    let params = {
        'id': row.id,
        'isTop': row.isTop
    }
    // 发送请求
    setArticleTop(params).then((res) => {
        // 渲染数据
        getTableData()
        if (res.success == true) {
            showMessage(row.isTop ? "置顶成功！" : "已取消置顶！")
        } else {
            showMessage(res.message, 'error')
        }
    })
}

// 跳转到文章详情页
const goArticleDetailPage = (id) => {
    router.push({path: '/article/detail/' + id})
}
</script>

<style scoped>
/* 封面图片样式 */
.avatar-uploader .avatar {
    width: 200px;
    height: 100px;
    display: block;
}

.el-icon.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 200px;
    height: 100px;
    text-align: center;
}
/* ::v-deep是vue3提供的深度选择器，.el-form-item__label是element-plus官方定义的类 */
::v-deep .el-form-item__label{
  font-weight: bold;
  font-size: 16px;
}
</style>

<style>
.md-editor-footer {
    height: 40px;
    font-size: 14px;
    font-weight: bolder;
}
</style>